<template>
    <div ref="scrollContainer" @scroll="handleScroll" class="order-container">
      <div v-for="order in orders" :key="order.orderId" class="order-item">
        <!-- 产品缩略图 -->
        <div class="product-image">
          <img :src="order.imgPath" alt="product image" />
        </div>
        
        <!-- 产品信息及订单状态 -->
        <div class="product-info">
          <h4>{{ order.productName }}</h4>
          <p>{{ order.info }}</p>
          <div class="order-status">
            <el-tag :type="getTagType(order.type)">
              {{ getOrderStatus(order.type) }}
            </el-tag>
          </div>
        </div>
        <div v-if="order.type === 1">
          <p>倒计时: {{ order.daedLine }}</p>
        </div>
        <!-- 订单操作 -->
        <div class="order-actions">
          <p>订单号: {{ order.orderNum }}</p>
          <p>价格: {{ order.coins}} 曼波币</p>
          <el-button 
            v-if="order.type === 1" 
            type="primary" 
            size="small" 
            @click="handlePay(order)"
          >支付</el-button>
          <el-button 
            v-else-if="order.type === 2" 
            type="success" 
            size="small" 
            disabled
          >已支付</el-button>
          <el-button 
            v-else 
            type="danger" 
            size="small" 
            disabled
          >订单失效</el-button>
        </div>
      </div>
  
      <!-- 加载更多状态 -->
      <div v-if="isLoading" class="loading-indicator">
        <el-spinner></el-spinner>
        <span>加载中...</span>
      </div>
  
      <div v-else-if="allLoaded" class="loading-indicator">
        <span>没有更多订单了</span>
      </div>
  
      <!-- 支付弹窗 -->
      <el-dialog v-model="isDialogVisible" title="订单支付" width="30%">
        <span>这是自定义的支付弹窗内容，订单号：{{ selectedOrder?.orderNum }}</span>
        <RQ :order-id="selectedOrder?.orderId"></RQ>
        <template #footer>
          <el-button @click="isDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmPayment">确认支付</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, onMounted,onBeforeUnmount } from 'vue';
  import { ElMessage } from 'element-plus';
  import { OrderProductDTO } from '@/interface/type';  // 导入定义的订单DTO类型
  import axios from 'axios';
  import { useUserStore } from '@/stores/user';
  import RQ from './components/RQ.vue';
  import { WebSocketMessageType } from '@/interface/type';
  import { eventBus } from '@/WebSocket/eventBus';
import router from '@/router';
  const userStore = useUserStore();
  
  // 数据定义
  const orders = ref<OrderProductDTO[]>([]);
  const isDialogVisible = ref(false);
  const selectedOrder = ref<OrderProductDTO | null>(null);
  const page = ref(1);  // 当前页面
  const size = ref(10);  // 每页大小
  const isLoading = ref(false);  // 是否正在加载
  const allLoaded = ref(false);  // 是否所有数据已加载

  const intervalId = ref<NodeJS.Timeout | null>(null); 
   eventBus.on('message-received', (message) => {
    const systemMessage = message.data;
  if (message.type === WebSocketMessageType.PAYMENT) {
    ElMessage({
      message: systemMessage.messageContent, // 显示消息内容
      type: systemMessage.messageType, // 成功类型展示
      duration: 3000,
      showClose: true,
    });
    isDialogVisible.value = false;
    console.log('Message received from WebSocket:', WebSocketMessageType.PAYMENT + systemMessage);
    router.go(0);
  }
})
  const fetchOrders = async () => {
  if (isLoading.value || allLoaded.value) return;  // 防止重复加载或超出数据加载
  isLoading.value = true;

  try {
    const res = await axios.get(`/api/orders/author/${userStore.userInfo.id}`, {
      params: {
        pageNum: page.value, // 确保后端分页机制使用正确的参数名
        pageSize: size.value,
      },
    });

    if (res.data.code !== 200) {
      ElMessage.error(res.data.message);
      isLoading.value = false;
      return;
    }

    const { listData, totalPages } = res.data.data;

    if (listData && listData.length > 0) {
      orders.value.push(...listData);  // 将新数据追加到现有的订单列表中
    }
    if (listData && listData.length > 0) {
      // 设定订单过期时间为创建时间 + 1 分钟
      listData.forEach((order: OrderProductDTO) => {
        if (order.type === 1 && order.orderCreatedAt) {
          const createdAt = new Date(order.orderCreatedAt).getTime();
          order.expiresAt = new Date(createdAt + 60 * 1000); // 创建时间 + 1 分钟
          order.deadLine = "";
        }
      });
      orders.value.push(...listData);
    }
    if (page.value >= totalPages) {
      allLoaded.value = true;  // 标记所有数据已加载完毕
    }

    page.value++;  // 页码递增
  } catch (error) {
    ElMessage.error('加载订单失败');
  } finally {
    isLoading.value = false;  // 结束加载状态
  }
};

  
  // 获取订单数据
  onMounted(async () => {
    await fetchOrders();
     // 启动倒计时定时器
  intervalId.value = setInterval(() => {
    orders.value.forEach((order) => {
      if (order.type === 1) {
        const remainingTime = getRemainingTime(order.expiresAt);
        order.daedLine = remainingTime;
        // 更新倒计时的显示内容
        if (remainingTime === '已过期') {
          order.type = 3; // 设置订单为失效
        }
      }
    });
  }, 1000); // 每秒更新一次
});


// 清除定时器
onBeforeUnmount(() => {
  if (intervalId.value) clearInterval(intervalId.value);
});

// 获取倒计时剩余时间
const getRemainingTime = (expiresAt: Date) => {
  const now = new Date().getTime();
  const remaining = expiresAt.getTime() - now;
  return remaining > 0 ? `${Math.floor(remaining / 1000)} 秒` : '已过期';
};
// 判断订单是否已过期
const isExpired = (expiresAt: Date) => {
  return new Date().getTime() >= expiresAt.getTime();
};

  // 获取订单状态文本
  const getOrderStatus = (type: number): string => {
    switch (type) {
      case 1:
        return '未支付';
      case 2:
        return '已支付';
      case 3:
        return '订单失效';
      default:
        return '';
    }
  };
  
  // 获取标签颜色类型
  const getTagType = (type: number): string => {
    switch (type) {
      case 1:
        return 'warning';
      case 2:
        return 'success';
      case 3:
        return 'danger';
      default:
        return '';
    }
  };
  
  // 处理支付点击
  const handlePay = (order: OrderProductDTO) => {
    selectedOrder.value = order;
    isDialogVisible.value = true;
  };
  
  // 确认支付
  const confirmPayment = () => {
    ElMessage.success(`订单 ${selectedOrder.value?.orderNum} 支付成功！`);
    isDialogVisible.value = false;
  };
  
// 处理滚动事件，加载更多数据
const handleScroll = async (event: Event) => {
  const container = event.target as HTMLElement;
  
  // 精确判断是否滚动到底部
  const nearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - 10;

  if (nearBottom) {
    // 滑动到底部时加载更多数据
    await fetchOrders();
  }
};

  </script>
  
  <style scoped>
  .order-container {
    padding: 20px;
    background-color: #f5f5f5;
    height: 80vh; /* 设定一个固定的高度来允许滚动 */
    overflow-y: auto; /* 允许垂直滚动 */
  }
  
  
  .order-item {
    display: flex;
    background-color: #fff;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  }
  
  .product-image img {
    width: 120px;
    height: 120px;
    object-fit: cover;
  }
  
  .product-info {
    flex: 1;
    margin-left: 20px;
  }
  
  .product-info h4 {
    font-size: 16px;
    font-weight: bold;
  }
  
  .product-info p {
    color: #606266;
    margin-top: 5px;
  }
  
  .order-status {
    margin-top: 10px;
  }
  
  .order-actions {
    text-align: right;
    min-width: 150px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }
  
  .loading-indicator {
    text-align: center;
    margin: 20px 0;
  }
  
  .el-spinner {
    margin-right: 10px;
  }
  </style>
  